package com.sky.Listen;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.sky.constant.MessageConstant;
import com.sky.dto.OrderMessageDto;
import com.sky.entity.Orders;
import com.sky.service.OrderService;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class Listener {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderService orderService;
    @Autowired
    private WebSocketServer webSocketServer;
    //监听死信队列
    @RabbitListener(queues = MessageConstant.sixinqueque)
    public void listen(OrderMessageDto orderMessageDto, Message message, Channel channel) throws IOException {
        log.info("监听死信队列");
        //判断死信队列的消息是已处理还是未处理
        Integer status= (Integer) redisTemplate.opsForHash().get("messagestatus", orderMessageDto.getId());
        if (status != null) {
            //已处理
            //手动确认ack
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } else {
            //未处理
            //更新数据库
            log.info("更新订单状态");
            Orders orders = Orders.builder()
                    .number(orderMessageDto.getId())
                    .cancelReason("订单超时")
                    .status(6)
                    .build();
            log.info("orderid is {},type",orderMessageDto.getId());
            orderService.update().eq("number", orderMessageDto.getId()).update(orders);
            //手动确认ack
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            webSocketServer.sendToAllClient("用户取消下单");
        }
    }
}
